<?php

namespace app\shop\controller\pay;

use think\Controller;
use think\Db;
use app\common\controller\Hm;
use think\Config;

/**
 * 云付天下支付类
 */
class Yfpay extends Controller {

    public $gateway_url = "https://yunfu.hmy3.com/api/gateway/request.html"; //云付天下网关地址
    public $domain = "";

    protected $site = []; //系统配置信息

    public $yfpay = []; //云付天下配置信息

    public function _initialize(){
        parent::_initialize(); // TODO: Change the autogenerated stub
        if(isset($_SERVER['REQUEST_SCHEME'])){
            $this->domain = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['HTTP_HOST'] . '/';
        }else{
            $this->domain = 'http://' . $_SERVER['HTTP_HOST'] . '/';
        }
        $this->site = Config::get("site");

        $yfpay_result = db::name('pay')->where(['type' => 'yfpay'])->find();
        $this->yfpay = json_decode($yfpay_result['value'], true);
    }



    /**
     * 发起云付天下支付
     * @params $order 订单信息
     * @params $goods 商品信息
     * @params $pay_type 支付类型 alipay  wxpay
     * @table 订单表 一般有商品订单表和余额充值订单表
     * M时参数必选，为O时可选，为C时需要依赖于其它字段
     */
    public function pay($order, $goods, $pay_type){
        
        $data = [
            'appid' => $this->yfpay['app_id'], // 应用id
//            'sub_mch_id' => '123456', //子商户号
            'type' => $pay_type, //交易通道
            'price' => $order['money'], //交易金额
            'name' => empty($this->site['diy_name']) ? $goods['name'] : $this->site['diy_name'], //商品名称
            'body' => empty($this->site['diy_name']) ? $goods['name'] : $this->site['diy_name'], //商品的详细说明
            'notify_url' => $this->domain . 'notify?mode_type=notify_yfpay', //支付完成后的异步回调通知地址
            'out_trade_no' => $order['order_no'], //商户订单号
            'ip' => getClientIp(), //付款用户的ip地址
            'server' => 'https://shop.hmy3.com/', //商家网站地址
        ];

        $data['sign'] = $this->getSign($data);

        // echo "<pre>"; print_r($data);

        $result = hmCurl($this->gateway_url, http_build_query($data), 1);
        
        // var_dump($result);die;
        
        $result = json_decode($result, true);
        
        if($result['state'] != "succeeded"){
            $this->error($result['message']);
        }
        //写入支付二维码
        db::name('order')->where(['id' => $order['id']])->update(['qr_code' => $result['return_data']['url']]);
        header("location: /aliprecreate.html?out_trade_no=" . $order['order_no']);
        die;
        

    }


    /**
     * 生成签名
     */
    public function getSign($data){
        ksort($data);
        $data_str = "";
        foreach($data as $key => $val) {
            if ($key != "sign"){
                $data_str .= $key . "=" . $val . "&";
            }
        }
        $data_str = rtrim($data_str, "&");
        $data_str = $data_str . $this->yfpay['app_key'];
        // echo $data_str;die;
        $sign = md5($data_str);
        $sign = strtolower($sign);
        return $sign;
    }

}
